<template>
  <div class="app-container">
    <div ref="action-container" class="action-container">
      <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="queryParams.username" clearable placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-plus" @click="handleCreate">新建</el-button>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          <el-button type="danger" icon="el-icon-delete" @click="handleDelete(selectedList.map(item => item.id).join(','))">批量删除</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-container">
      <el-table
        v-if="tableHeight"
        v-loading="loading"
        :data="list"
        border
        :height="tableHeight"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          :selectable="(row) => row.id != 1"
        />
        <el-table-column
          prop="username"
          label="用户名"
          width="180"
        />
        <el-table-column
          prop="phone"
          label="手机"
          width="180"
        />
        <el-table-column
          prop="email"
          label="邮箱"
          width="180"
        />
        <el-table-column
          prop="memo"
          label="备注"
        />
        <el-table-column
          fixed="right"
          label="操作"
          width="143"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.id != 1">
              <el-button size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
              <el-button type="danger" size="mini" @click="handleDelete(scope.row.id)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div ref="pagination-container" class="pagination-container">
      <pagination
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </div>
    <div class="extra-container">
      <el-dialog :destroy-on-close="true" :close-on-click-modal="false" width="500px" :visible.sync="showDialog" :title="form.id ? '更新': '添加'">
        <el-form ref="ruleForm" size="small" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="form.password" :disabled="(form.id && form.id == id)" type="password" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="确认密码" prop="password2">
            <el-input v-model="form.password2" :disabled="(form.id && form.id == id)" type="password" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="手机" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="备注" prop="memo">
            <el-input v-model="form.memo" type="textarea" :autosize="{ minRows: 3, maxRows: 3}" placeholder="请输入" />
          </el-form-item>
        </el-form>
        <template slot="footer">
          <el-button type="primary" size="small" @click="submitForm('ruleForm')">提交</el-button>
          <el-button size="small" @click="resetForm('ruleForm')">重置</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import * as userApi from '@/api/user'
import { mixins } from '@/mixins'
import { mapGetters } from 'vuex'
export default {
  mixins: [mixins],
  computed: {
    ...mapGetters([
      'id'
    ])
  },
  data() {
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      showDialog: false,
      loading: false,
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        username: ''
      },
      form: {},
      rules: {
        username: [
          { required: true, message: '请输入', trigger: 'blur' },
          { max: 30, message: '长度在30个字符以内', trigger: 'change' }
        ],
        password: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 6, max: 30, message: '长度在6到30个字符', trigger: 'change' }
        ],
        password2: [
          { required: true, message: '请输入', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' }
        ],
        phone: [{ max: 20, message: '长度在20个字符以内', trigger: 'change' }],
        email: [{ max: 30, message: '长度在30个字符以内', trigger: 'change' }],
        memo: [{ max: 150, message: '长度在150个字符以内', trigger: 'change' }]
      },
      list: [],
      selectedList: [],
      total: 0
    }
  },
  mounted() {
    this.handleQuery()
  },
  methods: {
    handleCreate() {
      this.form = {}
      this.showDialog = true
    },
    handleUpdate(row) {
      this.form = { ...row, password: '##thy##password', password2: '##thy##password' }
      this.showDialog = true
    },
    handleSelectionChange(rows) {
      this.selectedList = rows
    },
    handleDelete(id) {
      this.$confirm('此操作将永久删除账户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userApi.del({ id: id }).then(() => {
          this.handleQuery()
          this.$message({
            type: 'success',
            message: '删除成功'
          })
        })
      })
    },
    async handleQuery() {
      this.loading = true
      try {
        const { data } = await userApi.getList(this.queryParams)
        this.list = data.data
        this.total = data.total
      } catch (e) {
        console.log(e)
      } finally {
        this.loading = false
      }
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 15,
        username: ''
      }
      this.handleQuery()
    },
    submitForm(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          const data = { ...this.form }
          delete data.password2
          if (this.form.id) {
            await userApi.update(data)
          } else {
            await userApi.add(data)
          }
          this.handleQuery()
          this.$message({
            type: 'success',
            message: '保存成功'
          })
          this.showDialog = false
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style scoped lang="scss">

</style>

